Node.js 您所在的位置:网站首页 access var Node.js

Node.js

2024-07-01 12:50| 来源: 网络整理| 查看: 265

How to read environment variables from Node.js

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.

The below code runs app.js and set USER_ID and USER_KEY.

USER_ID=239482 USER_KEY=foobar node app.js BashCopy to clipboard

That will pass the user USER_ID as 239482 and the USER_KEY as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

Note: process does not require a "require", it's automatically available.

Here is an example that accesses the USER_ID and USER_KEY environment variables, which we set in above code.

process.env.USER_ID; // "239482" process.env.USER_KEY; // "foobar" JavaScriptCopy to clipboard

In the same way you can access any custom environment variable you set.

Node.js 20 introduced experimental support for .env files.

Now, you can use the --env-file flag to specify an environment file when running your Node.js application. Here's an example .env file and how to access its variables using process.env.

# .env file PORT=3000 BashCopy to clipboard

In your js file

process.env.PORT; // "3000" JavaScriptCopy to clipboard

Run app.js file with environment variables set in .env file.

node --env-file=.env app.js BashCopy to clipboard

This command loads all the environment variables from the .env file, making them available to the application on process.env

Also, you can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files.

node --env-file=.env --env-file=.development.env app.js BashCopy to clipboard

Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.

PrevRun Node.js scripts from the command lineNextHow to use the Node.js REPL


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有